package com.example.fruit.adapter;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.fruit.R;
import com.example.fruit.bean.Car;
import com.example.fruit.bean.Fruit;
import com.example.fruit.bean.Orders;
import com.example.fruit.bean.User;
import com.example.fruit.ui.activity.FruitDetailActivity;
import com.example.fruit.util.SPUtils;

import org.litepal.crud.DataSupport;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * 购物车适配器
 */
public class CarAdapter extends RecyclerView.Adapter<CarAdapter.ViewHolder> {
    private List<Car> list =new ArrayList<>();
    private Context mActivity;
    private RequestOptions headerRO = new RequestOptions().circleCrop();//圆角变换
    private LinearLayout llEmpty;
    private RecyclerView rvCarList;
    private ItemListener mItemListener;
    private String[] s=new String[]{"支付宝","银行卡","微信"};private int a=1;
    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void setItemListener(ItemListener itemListener){
        this.mItemListener = itemListener;
    }
    public CarAdapter(LinearLayout llEmpty, RecyclerView rvOrderList){
        this.llEmpty = llEmpty;
        this.rvCarList =rvOrderList;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        mActivity = viewGroup.getContext();
        View view= LayoutInflater.from(mActivity).inflate(R.layout.item_rv_car_list,viewGroup,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
        Car car = list.get(i);
        Fruit fruit = DataSupport.where("title = ?",car.getTitle()).findFirst(Fruit.class);
        User user = DataSupport.where("account = ? ", car.getAccount()).findFirst(User.class);
        if (car != null && user!=null && fruit != null) {
          //  viewHolder.j.setText(String.format("￥%s",car.getIssuer()));//order.getNumber
            viewHolder.title.setText(car.getTitle());
            Glide.with(mActivity)
                    .asBitmap()
                    .load(fruit.getImg())
                    .error(R.drawable.ic_error)
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(viewHolder.img);
            viewHolder.title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mActivity, FruitDetailActivity.class);
                    Fruit fruit = DataSupport.where("title = ?",car.getTitle()).findFirst(Fruit.class);
                    intent.putExtra("fruit",fruit);
                    mActivity.startActivity(intent);
                    return;
                }
            });
            float price = Float.parseFloat(fruit.getIssuer());
            viewHolder.j.setText("￥"+price*a);
            viewHolder.addBt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    a++;
                    viewHolder.tv.setText(a+"");
                    viewHolder.j.setText("￥"+price*a);
                }
            });
            viewHolder.minBt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                   int amount = Integer.parseInt(viewHolder.tv.getText().toString());//购买数量
                    if (amount > 1) {
                        a--;
                        viewHolder.tv.setText(a + "");
                        viewHolder.j.setText("￥"+price*a);
                    }else {
                        Toast.makeText(mActivity,"亲~不能再少了哦", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            viewHolder.zf.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String account = (String) SPUtils.get(mActivity,SPUtils.ACCOUNT,"");
                    if (!viewHolder.cb.isChecked()) {
                        Toast.makeText(mActivity, "您还没有选择商品哦！", Toast.LENGTH_LONG).show();
                    }else {
                        android.app.AlertDialog.Builder builder=new android.app.AlertDialog.Builder(mActivity);
                        builder.setIcon(R.drawable.a1);//设置图标
                        builder.setTitle("请选择支付方式");//设置对话框的标题
                        builder.setSingleChoiceItems(s,0,new DialogInterface.OnClickListener() {
                            @Override
                          public void onClick(DialogInterface dialog, int which) {
                                int i=which;
                            }
                        });
                        builder.setPositiveButton("确定",new DialogInterface.OnClickListener() {
                           @Override
                          public void onClick(DialogInterface dialog, int which) {
                           ProgressDialog dialog2 = new ProgressDialog(mActivity);
                           dialog2.setMessage("支付中···");
                           dialog2.show();
                           new Handler().postDelayed(new Runnable() {
                           @Override
                           public void run() {
                             //运行内容
                              int buyAmount,have,fruitAmount;
                              buyAmount = Integer.parseInt(viewHolder.tv.getText().toString());//购买数量
                              fruitAmount = Integer.parseInt(fruit.getAmount());//库存数量
                              have = fruitAmount-buyAmount;//被购买后剩余库存
                              if(buyAmount <= fruitAmount && buyAmount>0){
                                Orders orders = new Orders(account,viewHolder.tv.getText().toString(),fruit.getTitle(),"S"+System.currentTimeMillis(),viewHolder.j.getText().toString(),fruit.getImg(),sf.format(new Date()));//获取总毫秒数 从1970年1月1日开始计算
                                orders.save();
                                if (car!=null) {
                                   list.remove(car);
                                   car.delete();
                                   viewHolder.tv.setText("1");
                                   notifyDataSetChanged();//刷新数据
                                }
                                 if (list!=null && list.size() > 0){ rvCarList.setVisibility(View.VISIBLE);llEmpty.setVisibility(View.GONE);
                                 }else { rvCarList.setVisibility(View.GONE);llEmpty.setVisibility(View.VISIBLE);}

                                  Fruit newfirst = DataSupport.where("title = ?", fruit.getTitle()).findFirst(Fruit.class);
                                  newfirst.setAmount(have+"");//修改新的库存数量
                                  newfirst.save();

                                  dialog2.setMessage("支付成功！点击任意空白区域返回");
                                  Toast.makeText(mActivity,s[i]+"支付-成功,请在我的订单中查看!", Toast.LENGTH_SHORT).show();
                              }else{
                                  dialog2.setMessage("支付失败！点击任意空白区域返回");
                                  Toast.makeText(mActivity,"支付失败!购买数量不足或库存不足", Toast.LENGTH_SHORT).show();
                             }
                        }
                     }, 1500);
                 }
             });
                     builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                               @Override
                               public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(mActivity,"您取消了支付!", Toast.LENGTH_SHORT).show();
                               }
                           });
                     android.app.AlertDialog a=builder.create();
                     a.show();
                  }
              }
         });
                viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        AlertDialog.Builder dialog = new AlertDialog.Builder(mActivity);
                        dialog.setIcon(R.drawable.a1);//设置图标
                        dialog.setTitle("水果商城");//设置对话框的标题
                        dialog.setMessage("确认将该商品移出购物车吗?");
                        //消息框确认按钮
                        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                list.remove(car);
                                car.delete();
                                notifyDataSetChanged();//刷新数据
                                Toast.makeText(mActivity,"移除成功", Toast.LENGTH_LONG).show();
                                if (list!=null && list.size() > 0){
                                    rvCarList.setVisibility(View.VISIBLE);
                                    llEmpty.setVisibility(View.GONE);
                                }else {
                                    rvCarList.setVisibility(View.GONE);
                                    llEmpty.setVisibility(View.VISIBLE);
                                }
                            }
                        });
                        //消息框取消按钮
                        dialog.setNeutralButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        dialog.show();
                        return false;
                    }
                });
            }
        }

    public void addItem(List<Car> listAdd) {
        //如果是加载第一页，需要先清空数据列表
        this.list.clear();
        if (listAdd!=null){
            //添加数据
            this.list.addAll(listAdd);
        }
        //通知RecyclerView进行改变--整体
        notifyDataSetChanged();
    }
    @Override
    public int getItemCount() {
        return list.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder {
        private Button zf;
        private TextView j,tv;//价格和数量
        private LinearLayout ll_img;
        private Button addBt,minBt;
        private TextView title;
        private CheckBox cb;
        private ImageView img;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            zf=itemView.findViewById(R.id.zf);
            ll_img=itemView.findViewById(R.id.ll_img);
            title = itemView.findViewById(R.id.title);
            j=itemView.findViewById(R.id.j);
            cb=itemView.findViewById(R.id.cb);
            img=itemView.findViewById(R.id.img);
            addBt = itemView.findViewById(R.id.lv_item_add);
            minBt = itemView.findViewById(R.id.lv_item_min);
            tv = itemView.findViewById(R.id.lv_item_txt);
        }
    }
    public interface ItemListener{
        void ItemClick(Car car);
    }
}
